﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows;

namespace Freshome.m.vms
{
    internal class Recipes : TabItemate
    {
        private const string _ep = "wsHttp_IMultint";
        private readonly fox.Userole _ur = null;
        private readonly fox.Helproxy<Rmt.IMultint> _hp;
        private Rmt.RecipeCateg _ct;

        public Recipes(Rmt.RecipeCateg ct, string nm, fox.Userole ur)
            : base(nm, true)
        {
            this._ct = ct;
            this._ur = ur;
            this._hp = new fox.Helproxy<Rmt.IMultint>(ur);
            this._ld.DoWork += new DoWorkEventHandler(Load_DoWork);
            this._ld.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Load_WorkerCompleted);
            this.Content = new vws.Recipes() { DataContext = this };
        }
        private BackgroundWorker _ld = new BackgroundWorker();
        public fox.Userole Userole
        {
            get { return this._ur; }
        }
        public Rmt.RecipeCateg Category
        {
            get { return this._ct; }
        }
        public fox.Helproxy<Rmt.IMultint> Helproxy
        {
            get { return this._hp; }
        }
        public string Tellead
        {
            get
            {
                switch (this._ct)
                {
                    case Rmt.RecipeCateg.Coldish:
                        return "荤";
                    case Rmt.RecipeCateg.Dishot:
                        return "荤";
                    case Rmt.RecipeCateg.Snack:
                        return "馅";
                    case Rmt.RecipeCateg.Soupot:
                        return "汤";
                    case Rmt.RecipeCateg.Pastry:
                        return "米";
                    case Rmt.RecipeCateg.Drink:
                        return "热";
                    default: return string.Empty;
                }
            }
        }
        private ObservableCollection<mds.Recipe> _rps = new ObservableCollection<mds.Recipe>();
        public ObservableCollection<mds.Recipe> P_rps
        {
            get { return this._rps; }
        }
        public bool Readonly
        {
            get { return !Enabled; }
        }
        private bool _enabled = false;
        public bool Enabled
        {
            get { return _enabled && this._ur.IsJunior; }
            set
            {
                if (_enabled != value)
                {
                    _enabled = value;
                    OnPropertyChanged("Enabled");
                    OnPropertyChanged("Readonly");
                }
            }
        }
        // Recipes Loading finished
        void Load_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null) MessageBox.Show(e.Error.Message, "数据服务");
            else
            {
                var rts = e.Result as Rmt.Recipe[];
                if (rts != null)
                {
                    fox.Kitools.Refresh(rts, _rps);
                    foreach (var rt in rts)
                    {
                        var rp = _rps.FirstOrDefault(m => m.Raw.Mid == rt.Mid);
                        if (rt.Steps != null && rp != null)
                        {
                            fox.Kitools.Refresh(rt.Steps, rp.Steps);
                        }
                    }
                }
            }
            this.Enabled = true;
        }
        void Load_DoWork(object sender, DoWorkEventArgs e)
        {
            _hp.Asyncall(cln =>
            {
                e.Result = cln.GetRecipes(this._ct, false);
            }, new Rmt.MultintClient(_ep));
        }
        public override void Loadata()
        {
            if (!_ld.IsBusy)
            {
                _ld.RunWorkerAsync();
                this.Enabled = false;
            }
        }
        private void SaveRecipes(string category)
        {
            var rps = from r in _rps where (r.IsValid && r.Created) || r.Updated select r;
            if (rps.Count() > 0)
            {
                short mid = short.MinValue;
                foreach (var rw in rps)
                {
                    if (rw.Mid == default(short))
                    {
                        rw.Raw.Mid = mid++;
                        rw.Raw.Category = this._ct;
                    }
                    rw.Raw.Stamp = rw.Name;
                }
                Dictionary<short, string> rts = null;
                _hp.Syncall(cln =>
                {
                    rts = cln.SaveRecipes((from r in rps select r.Raw).ToArray());
                }, new Rmt.MultintClient(_ep));
                if (rts != null)
                {
                    fox.Kitools.Replace<mds.Recipe, Rmt.Recipe>(rts, rps, category);
                }
            }
        }
        private void SaveSteplans(string category)
        {
            short mid = short.MinValue;
            List<Rmt.Steplan> rws = new List<Rmt.Steplan>();
            foreach (var r0 in _rps.Where(m => m.Raw.Mid > default(short)))
            {
                var its = from p in r0.Steps where (p.Created && p.IsValid) || p.Updated select p.Raw;
                foreach (var r1 in its)
                {
                    if (r1.Mid == default(short))
                    {
                        r1.Mid = mid++;
                        r1.Rmx = r0.Raw.Mid;
                    }
                    r1.Stamp = string.Format("{0}+{1}", r0.Mid, r1.Planum);
                }
                rws = rws.Union(its).ToList();
            }
            if (rws.Count > 0)
            {
                Dictionary<short, string> rts = null;
                _hp.Syncall(cln =>
                {
                    rts = cln.SaveSteplans(rws.ToArray());
                }, new Rmt.MultintClient(_ep));
                if (rts != null)
                {
                    foreach (var r0 in _rps.Where(m => m.Raw.Mid > default(short)))
                    {
                        fox.Kitools.Replace<mds.Steplan, Rmt.Steplan>(rts, r0.Steps.Where(t => (t.Created && t.IsValid) || t.Updated), category);
                    }
                }
            }
        }
        private bool Savable()
        {
            return _rps.Any(m => (m.Created && m.IsValid) || m.Updated || m.Steps.Any(t => (t.IsValid && t.Created) || t.Updated));
        }
        private Magicommand _save;
        private void Saventry()
        {
            string category = Properties.Resources.ResourceManager.GetString(this._ct.ToString());
            SaveRecipes(category);
            SaveSteplans(category);
        }
        public Magicommand Save
        {
            get
            {
                if (_save == null) _save = new Magicommand(Properties.Resources.Save + "(_S)", param => this.Saventry(), param => this.Savable());
                return _save;
            }
        }
    }
}
